const { BASE_URL } = require('../config.js');

Page({
  data: {
    dishList: [],
    filteredDishes: [],
    categories: [],
    currentCategory: '全部',
    categoryMap: {},
    banners: [
      { image: '../../images/banner1.jpg' },
      { image: '../../images/banner2.jpg' },
      { image: '../../images/banner3.jpg' }
    ],
    isLoggedIn: false,
    tableId: null,
    cartList: [], // 购物车列表
    showCart: false, // 是否显示购物车弹窗
    showOrderList: false, // 是否显示订单列表弹窗
    orderList: [], // 订单列表
    cartTotal: 0,
    payOrderButtonDisabled: false,
    payOrderButtonText: '支付',
    // 分类名与categoryId的固定映射
    categoryNameToId: {
      '主食': 1,
      '小吃': 2,
      '酒水饮料': 3,
      '特色炒饭': 4,
      '汤品': 5,
      '甜品': 6,
      '其他': 7
    },
    // 订单状态映射
    orderStatusMap: {
      1: '等待制作中',
      2: '制作中',
      3: '制作完成',
      4: '待上菜',
      5: '已上菜',
      6: '已完成'
    },
  },

  onLoad(options) {
    // 获取菜单列表
    this.getDishList();
    // 获取分类列表
    this.getCategories();
    //   const tableId = options.tableId || null;  // 实际上线的逻辑
    const tableId = 12;  // 开发方便的逻辑
  
    if (tableId) {
      this.setData({ tableId });

      // 保存到本地，方便后续页面使用
      wx.setStorageSync('tableId', tableId);

      console.log('扫码进入，桌号是：', tableId);
    } else {
      console.warn('未携带桌号参数');
    }
  },

  getDishList(categoryName) {
    console.log('准备请求');
    let data = {
      pageNum: 1,
      pageSize: 100
    };
    if (categoryName && categoryName !== '全部') {
      // 通过映射获取categoryId
      const categoryId = this.data.categoryNameToId[categoryName];
      if (categoryId) {
        data.categoryId = categoryId;
      }
    }
    const token = wx.getStorageSync('token') || '';
    wx.request({
      url: BASE_URL + '/dish/list',
      method: 'POST',
      data: data,
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: (res) => {
        console.log('请求结果', res);
        if (res.data.code === 1) {
          const baseUrl = BASE_URL + '/images/';
          const dishes = res.data.data.data.map(dish => {
            // 只取文件名部分
            let imgName = dish.image;
            if (imgName.startsWith('D:/upload/')) {
              imgName = imgName.replace('D:/upload/', '');
            }
            return {
              ...dish,
              image: baseUrl + imgName
            }
          });
          this.setData({
            dishes,
          }, () => {
            this.filterDishes();
          });
        } else {
          wx.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.log('请求失败', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  getCategories() {
    const token = wx.getStorageSync('token') || '';
    wx.request({
      url: BASE_URL + '/category/list',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: (res) => {
        if (res.data.code === 1) {
          // 只保留status不为0的分类
          const validCategories = res.data.data.filter(cat => cat.status !== 0);
          // 构建categoryMap: id -> name
          const categoryMap = {};
          validCategories.forEach(cat => {
            categoryMap[cat.id] = cat.name;
          });
          // 构建categories数组，首位为'全部'
          const categories = ['全部', ...validCategories.map(cat => cat.name)];
          this.setData({
            categories,
            currentCategory: '全部',
            categoryMap
          }, this.filterDishes);
        } else {
          wx.showToast({
            title: '获取分类失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  wxLogin() {
    wx.login({
      success: res => {
        if (res.code) {
          // 这里可以把 code 发送到后端换 openid 或 session
          console.log('微信登录code:', res.code);
        
          const token = wx.getStorageSync('token') || '';
          wx.request({
            url: BASE_URL + '/wxlogin',
            method: 'POST',
            data: { code: res.code },
            
            success: (result) => {
              // 处理后端返回的用户信息
              console.log("后端返回:",result.data);
              wx.setStorageSync('token', result.data.token);
              this.setData({ isLoggedIn: true });
              console.log("登录状态:",this.data.isLoggedIn);
              this.getDishList();
            }
          });
        } else {
          wx.showToast({
            title: '微信登录失败',
            icon: 'none'
          });
          console.error('登录失败！' + res.errMsg);
        }
      }
    });
  },

  switchCategory(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      currentCategory: category
    }, () => {
      this.getDishList(category);
    });
  },

  filterDishes() {
    const { currentCategory, dishes, categoryMap, cartList } = this.data;
    // 先构建一个 id->count 的 map
    const cartMap = {};
    cartList.forEach(item => {
      cartMap[item.id] = item.count;
    });
    let filtered = [];
    if (currentCategory === '全部') {
      filtered = dishes;
    } else {
      let categoryId = null;
      for (let key in categoryMap) {
        if (categoryMap[key] === currentCategory) {
          categoryId = key;
          break;
        }
      }
      filtered = dishes.filter(d => String(d.categoryId) === String(categoryId));
    }
    // 给每个菜品加 cartCount 字段
    filtered = filtered.map(dish => ({
      ...dish,
      cartCount: cartMap[dish.id] || 0
    }));
    this.setData({ filteredDishes: filtered });
  },

  goToDetail(e) {
    const dish = e.currentTarget.dataset.dish
    wx.navigateTo({
      url: `/pages/dishDetail/dishDetail?dish=${encodeURIComponent(JSON.stringify(dish))}`
    })
  },

  onCancelLogin() {
    const tableId = wx.getStorageSync('tableId');
    wx.showToast({
      title: '取消登录,当前桌号是:' + tableId,
      icon: 'none'
    });
  },

  onDishTap(e) {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先微信登录授权',
        icon: 'none'
      });
      return;
    }
    const dish = e.currentTarget.dataset.dish;
    wx.navigateTo({
      url: `/pages/dishDetail/dishDetail?dish=${encodeURIComponent(JSON.stringify(dish))}`
    });
  },

  // 新增逻辑
  addToCart(e) {
    const dish = e.currentTarget.dataset.dish;
    let cartList = this.data.cartList.slice();
    const idx = cartList.findIndex(item => item.id === dish.id);
    if (idx > -1) {
      cartList[idx].count += 1;
    } else {
      cartList.push({ ...dish, count: 1 });
    }
    this.setData({ cartList });
    this.filterDishes();
    this.updateCartTotal();
  },

  removeFromCart(e) {
    const dish = e.currentTarget.dataset.dish;
    let cartList = this.data.cartList.slice();
    const idx = cartList.findIndex(item => item.id === dish.id);
    if (idx > -1) {
      cartList[idx].count -= 1;
      if (cartList[idx].count <= 0) {
        cartList.splice(idx, 1);
      }
    }
    this.setData({ cartList });
    this.filterDishes();
    this.updateCartTotal();
  },

  showCartPopup() {
    this.setData({ showCart: true });
    this.updateCartTotal();
  },

  hideCartPopup() {
    this.setData({ showCart: false });
  },

  updateCartTotal() {
    const cartList = this.data.cartList.map(item => ({
      ...item,
      total: (item.price * item.count).toFixed(2)
    }));
    // 计算总价
    const cartTotal = cartList.reduce((sum, item) => sum + Number(item.total), 0).toFixed(2);
    this.setData({ cartList, cartTotal });
  },

  submitOrder() {
    const { cartList, tableId } = this.data;
    if (!cartList.length) {
      wx.showToast({ title: '购物车为空', icon: 'none' });
      return;
    }
    let successCount = 0;
    let failCount = 0;
    const that = this;
    // 顺序下单，每次间隔0.5秒
    function submitOne(index) {
      const token = wx.getStorageSync('token') || '';
      if (index >= cartList.length) {
        if (failCount === 0) {
          wx.showToast({ title: '下单成功', icon: 'success' });
          that.setData({ cartList: [], showCart: false });
          that.updateCartTotal();
        } else if (successCount === 0) {
          wx.showToast({ title: '下单失败', icon: 'none' });
        } else {
          wx.showToast({ title: '部分下单失败', icon: 'none' });
        }
        return;
      }
      const item = cartList[index];
      wx.request({
        url: BASE_URL + '/order/add',
        method: 'POST',
        data: {
          dishId: item.id,
          tableId: tableId,
          count: item.count,
          amount: item.price
        },
        header: {
          'content-type': 'application/json',
          'token': token
        },
        success: (res) => {
          if (res.data.code === 1) {
            successCount++;
          } else {
            failCount++;
          }
          setTimeout(() => {
            submitOne(index + 1);
          }, 500);
        },
        fail: () => {
          failCount++;
          setTimeout(() => {
            submitOne(index + 1);
          }, 500);
        }
      });
    }
    submitOne(0);
  },

  showOrderListPopup() {
    this.getOrderList();
    this.setData({ showOrderList: true });
  },

  hideOrderListPopup() {
    this.setData({ showOrderList: false });
  },

  getOrderList() {
    const tableId = this.data.tableId;
    const token = wx.getStorageSync('token') || '';
    wx.request({
      url: BASE_URL + '/order/list',
      method: 'POST',
      data: {
        tableId: tableId,
        pageNum: 1,
        pageSize: 100,
        status: 7 // 7是特殊值,用于获取用户订单的列表
      },
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: (res) => {
        if (res.data.code === 1) {
          const orderList = res.data.data.data || [];
          // 批量获取菜品信息
          this.fetchDishesForOrders(orderList);
        } else {
          wx.showToast({ title: '获取订单失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 新增方法
  fetchDishesForOrders(orderList) {
    const that = this;
    // 用Promise.all批量请求
    const requests = orderList.map(order => {
      return new Promise((resolve) => {
        const token = wx.getStorageSync('token') || '';
        wx.request({
          url: BASE_URL + '/dish/list',
          method: 'POST',
          data: {
            id: order.dishId,
            pageNum: 1,
            pageSize: 1
          },
          header: {
            'content-type': 'application/json',
            'token': token
          },
          success: (res) => {
            if (res.data.code === 1 && res.data.data.data.length > 0) {
              const dish = res.data.data.data[0];
              // 合并图片和名称到订单
              resolve({
                ...order,
                dishImage: BASE_URL + '/images/' + dish.image,
                dishName: dish.name,
                orderStatusText: that.data.orderStatusMap[order.status] || order.status
              });
            } else {
              resolve({
                ...order,
                orderStatusText: that.data.orderStatusMap[order.status] || order.status
              });
            }
          },
          fail: () => {
            resolve({
              ...order,
              orderStatusText: that.data.orderStatusMap[order.status] || order.status
            });
          }
        });
      });
    });

    Promise.all(requests).then(newOrderList => {
      that.setData({ orderList: newOrderList });
    });
  },

  payOrder() {
    // 这里只做演示，假设支付第一个订单
    const orderList = this.data.orderList;
    if (!orderList || orderList.length === 0) {
      wx.showToast({ title: '暂无可支付订单', icon: 'none' });
      return;
    }
    const orderId = orderList[0].orderId; // 可根据实际需求选择订单
    console.log("orderId",orderId);
    const token = wx.getStorageSync('token') || '';
    wx.request({
      url: BASE_URL + '/notify',
      method: 'POST',
      data: { id: orderId },
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({ title: '支付成功', icon: 'success' });
          this.setData({
            payOrderButtonDisabled: true,
            payOrderButtonText: '已支付'
          });
        } else {
          wx.showToast({ title: '支付失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
})
